/*
 * $Id: ExampleSupport.java 471756 2006-11-06 15:01:43Z husted $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.nk.system.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.nk.system.beans.UploadDocumentBean;
import com.nk.system.beans.UserProfileBean;
import com.nk.system.utils.UI_Constants;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Base Action class for the Tutorial package.
 */
public class ActionBaseSupport extends ActionSupport implements
SessionAware, ServletRequestAware, ServletResponseAware {
	/**
	 * 
	 */
	private Logger log = Logger.getLogger(ActionBaseSupport.class);
	private static final long serialVersionUID = 1L;
	private Map session;
	private HttpServletRequest request;
	private HttpServletResponse response;

	protected static final String RESULT_SUCCESS = "resultSuccess";
	protected static final String RESULT_INVALID = "invalid";
	protected static final String RESULT_JSON = "resultJSon";
	protected static final String RESULT_VIEW_FILE = "viewFile";
	protected static final String RESULT_FILE_RESULT = "fileResult";
	
	private byte[] imageInByte = null;
	private String imageId;
  
	protected UserProfileBean getUserProfile() {
		UserProfileBean userProfileBean = (UserProfileBean)getServletRequest().getSession().getAttribute(UI_Constants.SESS_ATTR_USER_ACCESS);
		return userProfileBean;
	}
	@SuppressWarnings("unchecked")
	public void setSession(Map session) {
		this.session = session;
	}

	@SuppressWarnings("unchecked")
	public Map getSession() {
		return session;
	}
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletRequest getServletRequest() {
		return request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletResponse getServletResponse() {
		return response;
	}

	/*public HttpSession getSession() {
		return getServletRequest().getSession();
	}
	
	public HttpSession getSession(boolean arg0) {
		return getServletRequest().getSession(arg0);
	}*/
	

	
	protected Integer getUnitWater(Integer value) {
		Integer weight = Integer.valueOf(ServletActionContext.getServletContext().getInitParameter("WATER_WEIGHT"));
		Integer min = Integer.valueOf(ServletActionContext.getServletContext().getInitParameter("WATER_WEIGHT_MIN"));
		Integer max = Integer.valueOf(ServletActionContext.getServletContext().getInitParameter("WATER_WEIGHT_MAX"));
		if(value <= weight) {
			return min;
		}else {
			return max;
		}
	}
	
	protected Integer amountService() {
		return Integer.valueOf(ServletActionContext.getServletContext().getInitParameter("Amount_Service"));
	}
	
	protected void clearFileUPLOAD_DOCUMENT_AUTO() {
		 /**
         * clear documentUpload in Session
         */
		Object obj = getServletRequest().getSession().getAttribute(UI_Constants.SESS_ATTR_UPLOAD_DOCUMENT_AUTO);
        if(obj != null) {
        	List<UploadDocumentBean> documentUploadBeanList = (ArrayList<UploadDocumentBean>)obj;
        	for(UploadDocumentBean uploadDocumentBean:documentUploadBeanList) {
        		String filePath = ServletActionContext.getServletContext().getInitParameter("PATH_SERVER_AUTOMOBILE")+File.separator+uploadDocumentBean.getUploadFilename();
        		log.info("File = "+filePath);
        		File file = new File(filePath);
        		if(file.exists()) {
        			log.info("File Deleted. ");
        			file.delete();
        		}
        	}
        }
	}
	
    public String fileResult(){
    	
    	return RESULT_FILE_RESULT;
    }
	
	public byte[] getCustomImageInBytes() {
		 
		System.out.println("imageId" + imageId);
 
		BufferedImage originalImage;
		try {
			originalImage = ImageIO.read(getImageFile(this.imageId));
			// convert BufferedImage to byte array
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(originalImage, imageId.substring(imageId.lastIndexOf(".")+1,imageId.length()), baos);
			baos.flush();
			imageInByte = baos.toByteArray();
			baos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
		return imageInByte;
	}
 
	private File getImageFile(String imageId) {
		String filePath = ServletActionContext.getServletContext().getInitParameter("PATH_SERVER_AUTOMOBILE");
		File file = new File(filePath + File.separator, imageId);
		System.out.println(file.toString());
		return file;
	}
	
	protected void readFile(String fileRequest) throws IOException {

		String contentType = getServletRequest().getSession().getServletContext().getMimeType(fileRequest);  
        getServletResponse().setContentType(contentType);  
        //New  
        getServletResponse().setHeader("Expires", "0");  
        getServletResponse().setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");  
        getServletResponse().setHeader("Pragma", "public");  
          
        OutputStream out = getServletResponse().getOutputStream();  
        String filePath = ServletActionContext.getServletContext().getInitParameter("PATH_SERVER_AUTOMOBILE");
        byte[] pdfContent = loadFile(filePath+File.separator+fileRequest);  
        out.write(pdfContent, 0, pdfContent.length);   
        if (out != null) {  
            out.close();  
        }  
	}
    
    public static byte[] loadFile(String sourcePath) {  
        byte[] output = null;  
        try {  
        	File f = new File(sourcePath);
        	int length = (int)f.length();
        	output = new byte[length];
        	FileInputStream fin = new FileInputStream(f);
        	DataInputStream din = new DataInputStream(fin);
        	din.read(output);
        }   
        catch(IOException ioex) {  
        	ioex.printStackTrace();
        }         
  
        return output;  
    }  
 
	public String getCustomContentType() {
		return "image/jpeg";
	}
 
	public String getCustomContentDisposition() {
		return "anyname.jpg";
	}
	
	public byte[] getImageInByte() {
		return imageInByte;
	}
	public void setImageInByte(byte[] imageInByte) {
		this.imageInByte = imageInByte;
	}
	public String getImageId() {
		return imageId;
	}
	public void setImageId(String imageId) {
		this.imageId = imageId;
	}

}
